var workIndex = 0;
var workUrl = salesURL[0];
var requestData;
var tree = {}, showAll = true, selectNode = {}, moveNode = {};
var picUrl = '../dealer/images/images/tree/';
var contexNode = {}; //右键打开节点对象
var selectTab = 0; //左侧当前导航标记
//通过其中的几个值决定在其他页面显示的时候是否从新加载页面 /true 表示不需要重新加载，false表示重新加载
var reloadTreeFlag = {taxfee:true,revenue:true,message:true,overtree:true,homesale_q:true,homesale_b:true};

$(function(){
	var pageCanvas = top.document.documentElement;
	var w = pageCanvas.clientWidth;
	var h = pageCanvas.clientHeight;
	if(w < 800){w = 800;}
	if(h < 400){h = 400;}
	document.getElementById('rightFram_container').style.height = (h-112)+"px";
	document.getElementById('contentFrame').style.height = (h-289)+"px";

	var rMenu = $("#rMenu"), setting = {
			data: {
				key: {
					title: "title"
				}
			},
			edit: {
				enable: true,
				showRemoveBtn: false,
				showRenameBtn: false
			},
			async: {
				enable: true,
				url: treeLoadUrl(),
				autoParam: ["id=cust_id"],
				dataFilter: filter
			},
			callback: {
				onRightClick: onRightClick,
				beforeDrop:  function(treeId, treeNodes, targetNode, moveType){ return onDrop(treeId, treeNodes, targetNode, moveType);},
				beforeRightClick: function(){return !selectTab;},
				onClick: function(event, treeId, node, clickFlag){treeOnclickCallBack(node, event);},
				onNodeCreated: function(event, treeId, treeNode){if(!treeNode.pId && treeNode.level == 0){tree.selectNode(treeNode);tree.reAsyncChildNodes(treeNode, "refresh");treeOnclickCallBack(treeNode);}}
			}
		};
		
		function filter(treeId, parentNode, childNodes) {
			if(!parentNode){
				childNodes = [{text:login_user.text + "(" + top.login_msg.selfNum + "/" + top.login_msg.total + ")", id:login_user.id, leaf: false}];
			}
			for (var i=0, l = childNodes.length; i<l; i++) {
				var parent = !childNodes[i].leaf;
				childNodes[i].name = childNodes[i].text;
				childNodes[i].isParent = parent;
				childNodes[i].icon = parent ? picUrl + 'folder.gif' : picUrl + 'leaf.gif';
				childNodes[i].title = getNodeTitle(childNodes[i].text);
			}
			return childNodes;
		}
		
		function onDrop(treeId, treeNodes, targetNode, moveType){
			var node = treeNodes[0], newParent = targetNode;
			if(node.pid == newParent.id) return false;
			if(!confirm(top.lg.moveCustom[0]+'\''+node.text.split('(')[0]+'\''+top.lg.moveCustom[1]+'\''+newParent.text.split('(')[0]+'\''+top.lg.moveCustom[2]+'')){
				return false;
			}else{
				$.ajax({
					url : 'changeSchoolRelation.jsp',
					type : 'POST',
					data : { custId: node.id, parentId: newParent.id, schoolId: login_user.id },
					success : function(response , options) {
						top.reloadTreeRequest("reloadTree=1&from_id="+node.id+"&to_id="+newParent.id+"&need_num=1&op_type=move");
						reloadTreeFlag = {taxfee:false, revenue:false, message:false, overtree:false, homesale_q:false, homesale_b:false};
						if(workIndex == 2){selectSales(2,salesURL[2]);}
						tree.selectNode( node );
					}
				});
			}			
		}
		
		function onRightClick(event, treeId, treeNode) {
			if(treeNode){ 
				contexNode = {id: treeNode.id, name: treeNode.name, text: treeNode.name, tId: treeNode.tId, isParent:treeNode.isParent};
				if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
					tree.cancelSelectedNode();
					showRMenu("root", event.clientX, event.clientY);
				} else if (treeNode && !treeNode.noR) {
					tree.selectNode(treeNode);	
					showRMenu("node", event.clientX, event.clientY);
				}
			}
		}

		function showRMenu(type, x, y) {
			y = y + 182 > $('body').height() ? y - 182 : y;
			rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
			$("body").bind("mousedown", onBodyMouseDown);
		}
		function hideRMenu() {
			if (rMenu) rMenu.css({"visibility": "hidden"});
			$("body").unbind("mousedown", onBodyMouseDown);
		}

		function onBodyMouseDown(event){
			if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
				rMenu.css({"visibility" : "hidden"});
			}
		}		
		//初始化树
		$.fn.zTree.init($("#tree0"), setting);
		tree = $.fn.zTree.getZTreeObj("tree0");
		$('#treeContainer').css({height: h-191});
		
		//刷新
		$('.refreshc').html(top.lg.refresh).click(function(){
			var n = tree.getNodeByTId(contexNode.tId);
			if(n) tree.reAsyncChildNodes(n, "refresh", true);
			rMenu.css({"visibility" : "hidden"});
			return false;
		});
		//销售设备
		$('.salec').html(top.lg.sale+top.lg.pro).click(function(){
			top.win.closeWinLayer();
			treeOnclickCallBack(contexNode, null);
			top.win.openWinLayer(top.lg.sale,getSaleUrl(),600,440,2,window,null);
			rMenu.css({"visibility" : "hidden"});
			return false;
		});
		//新增客户
		$('.newc').html(top.lg.add+top.lg.client).click(function(){
			var node = contexNode;
			selectNode = contexNode;
			top.win.openWinLayer(top.lg.addutit,"newCustom.jsp?p_id="+node.id+"&name="+encodeURIComponent(node.text),550,400,2,window,null);
			rMenu.css({"visibility" : "hidden"});
			return false;
		});
		//管理客户
		$('.mangerc').html(top.lg.manage+top.lg.client).click(function(){
			var node = contexNode;
			top.win.openWinLayer(top.lg.updateUTit,"customUpdate.jsp?custid="+node.id,500,330,2,window,null);
			rMenu.css({"visibility" : "hidden"});
			return false;
		});
		//删除客户
		$('.delc').html(top.lg.del+top.lg.client).click(function(){
			rMenu.css({"visibility" : "hidden"});
			var node = contexNode;
			deleteID = node.tId;
			nodeID = node.id;
			if(!confirm(top.lg.client+':'+node.text.split('(')[0]+'\r\n'+top.lg.delUTip))return;
			$.ajax({
				dataType : "jsonp",
				jsonp: 'callback',
				url : top.updateUrl+"GetDataService?method=deleteEnterprise&callback=delCallback&mds="+top.mds,
				data :"id="+node.id
			});	
			return false;
		});
		//重置密码
		$('.resetc').html(top.lg.resetPwd).click(function(){
			rMenu.css({"visibility" : "hidden"});
			var node = contexNode;
			if(!confirm(top.lg.client+'：'+node.text.split('(')[0]+'\r\n'+top.lg.resetpwdtip))return;
			$.ajax({
				dataType : "jsonp",
				jsonp: 'callback',
				url : top.updateUrl+"GetDataService?method=resetCustomerPWD&callback=resetPassCallback&mds="+top.mds,
				data :"school_id="+node.id
			});		
			return false;
		});
		//客户转移
		$('.movec').html(top.lg.cMove).click(function(){
			rMenu.css({"visibility" : "hidden"});
			var node = contexNode;
			moveNode = tree.getNodeByParam('id',node.id,null);
			top.win.openWinLayer(top.lg.cMove,"customMove.jsp?custid="+node.id+"&name="+encodeURIComponent(node.text),430,250,2,window,null);
			return false;
		});
		
		$('#rMenu li').hover(function(){$(this).addClass('li-hover');}, function(e){$(this).removeClass('li-hover');});
		$(window).load(function(){selectSales(1, salesURL[1]);});
		if(top.login_msg) loadLoginMessage(top.login_msg);
});

//产生节点的tip提示文字
function getNodeTitle(nodeText){
	try{
		if(selectTab == 0){
			var gr = nodeText.match(/\(\d+\/\d+\)$/);
			var ns = gr[0].match(/\d+/g);
			return top.lg.tipDeviceNum.replace("{0}", ns[0]).replace("{1}", ns[1]);
		}
		else if (selectTab == 1){
			var gr = nodeText.match(/\(\d+\)$/);
			var ns = gr[0].match(/\d+/g);
			return top.lg.tipBill.replace("{0}", ns[0]);
		}
		else{
			var gr = nodeText.match(/\(\d+\)$/);
			var ns = gr[0].match(/\d+/g);
			return top.lg.tipCharge.replace("{0}", ns[0]);
		}
	}catch(ex){
		return nodeText;
	}
}

//动态树加载的参数
function treeLoadUrl(action, loadParams) {
	action = action || 'getTreeByCustId.jsp'; 
	var p = "../dealer/" + action + "?school_id=-1" + "&mds=" + top.mds;
	return loadParams ? p + loadParams : p;
}

//选择打开右侧页签栏
function selectSales(index,url){
	workUrl = url;
	var _d = new Date().getMilliseconds();
	var url = url+"&custid="+overCust.custid;
	var pPage = top.GetCookie("pPage");
	if(pPage==""||pPage==null)pPage=20;
	var cPage = top.GetCookie("cPage");
	if(cPage==""||cPage==null)cPage=20;
	if(index==1||index==2){
		url = url+"&cpage="+cPage+"&ppage="+pPage;
	}else if(index==3){
		url = url+"&expireScope="+expireScopeType[0];
	}else if(index==4){
		url = url+"&expireScope="+expireScopeType[1];
	}
	var el = document.getElementsByName('navigate_');
	for(var i=0;i<el.length;i++){
		if(index == i){
			el[i].parentNode.parentNode.id="navigate_item_over";
			el[i].parentNode.parentNode.style.zoom = 1; //ie6 fix
			overCust.treeType = i;
		}else{
			el[i].parentNode.parentNode.id = '';
			el[i].parentNode.parentNode.style.zoom = 0; //ie6 fix
		}
	}
	document.getElementById('contentFrame').src = url+"&ecar="+_d;		
	workIndex = index;
}

//打开右侧页签栏url地址
function getSaleUrl(){
	var _d = new Date().getMilliseconds();
	var url = salesURL[0]+"&custid=" + overCust.custid;
	return url + "&ecar=" + _d;	
}

//防止节点重复点击加载
function treeOnclickCallBack(node,e){
	overCust.custid = node.id;
	overCust.custname = node.name;
	if(requestData != "cust_id="+node.id){
		selectSales(workIndex,workUrl);	
		loadCustonMessage("getEntrpriseNumInfo.jsp","cust_id="+node.id);
	}
}
//浏览器resize处理方法
function syncSize(){	
	var pageCanvas = top.document.documentElement;
	var w = pageCanvas.clientWidth;
	var h = pageCanvas.clientHeight;
	if(w<800){w=800;} if(h<400){h=400;}
	$('#treeContainer').css({height: h-191});
	document.getElementById('rightFram_container').style.height = (h-112)+"px";
	document.getElementById('contentFrame').style.height = (h-289)+"px";
}

//获取选择客户信息
function loadCustonMessage(url,data){
	requestData = data;
	$.ajax({
	   url: url+'?'+data,
	   dataType: 'json',
	   success: function(x,opt){
			loadLoginMessage(x);
		}
	});
}

//右侧显示客户信息
function loadLoginMessage(obj){
	var gradeDate = top.lg.gradeDate;
	if(obj.id == "1000000"){
		obj.total=0; obj.selfNum=0; obj.flatNum=0; obj.supplyNum=0;
	}
	var objArr = ["id","login_name","grade","name","address","contact","phone","total","selfNum"];//"flatNum","supplyNum"
	for(var i=1;i<objArr.length;i++){
		if(i==2){
			var tem = 'c'+objArr[i];
			document.getElementById(objArr[i]).innerHTML = eval("gradeDate.c" + obj[objArr[i]]);
		} else 
			document.getElementById(objArr[i]).innerHTML = obj[objArr[i]];
	}
}

//删除客户回调
var deleteID=-1;
var nodeID=-1;
function delCallback(obj){
	alert(top.lg.delCallTip[Number(obj.status)]);
	if(obj.success){
		top.reloadTreeRequest("reloadTree=1&from_id="+nodeID+"&op_type=delete");
		var node = tree.getNodeByTId(deleteID);
		if(node){
			var parent = node.getParentNode();
			tree.removeNode(node);
			parent.icon = picUrl + (parent.childs ? 'folder.gif' : 'leaf.gif');
			tree.updateNode(parent);			
			reloadTreeFlag = {taxfee:false,revenue:false,message:false,overtree:false,homesale_q:false,homesale_b:false};
			if(workIndex == 2){selectSales(2,salesURL[2]);}
		}
	}
}

//重置密码回调方法
function resetPassCallback(obj){
	alert(obj.success ? top.lg.resetpwdsuc + ':123456' : top.lg.resetpwdfail);
}

//点击左侧导航栏方法
function getselect(name,num,sid,flag){
	selectTab = num;
	var el = document.getElementsByName(name);
	for(var i = 0; i < el.length; i++){
		if(num == i){
			el[i].parentNode.parentNode.id = sid;
			el[i].parentNode.parentNode.style.zoom = 1; //ie6 fix
			overCust.treeType = i;
			if(flag) show(i);
		}else{
			el[i].parentNode.parentNode.id = '';
			el[i].parentNode.parentNode.style.zoom = 0; //ie6 fix
		}
	}	
	if(num >=1){
		selectSales(2 + num, salesURL[2 + num]);
		tree.setting.async.url = treeLoadUrl('getExpireTreeByCustId.jsp', '&begin=&end=&expireScope=-1&type=' + (--num));
	}else{
		tree.setting.async.url = treeLoadUrl('');
	}
	//切换页签时更新根节点显示信息
	var n = tree.getNodeByParam('id',login_user.id,null);
	if(n){
		var msg = !selectTab ? login_user.text + "(" + top.login_msg.selfNum + "/" + top.login_msg.total + ")" : (login_user.text + "(" + (selectTab == 1 ? top.login_msg.flatNum : top.login_msg.flatNum) + ")");
		n.name = msg;
		n.title = getNodeTitle(msg);
		tree.updateNode(n);	
	}	
	//重新请求数据
	tree.refresh();
}

//选择左侧页签显示不同的客户树内容
function show(i){
	var con = $('#filter-con');
	$('option:first', con).attr('selected','selected');
	var h = top.document.documentElement.clientHeight;
	if(i == 0){
		con.hide();
	}else{
		con.show();
		if(i == 1){
			reloadTreeFlag.taxfee = true;
		}else{
			reloadTreeFlag.revenue = true;
		}	
	}
}
//缴费收费中选择过期类型
function treeReload(expireScope){
	var num = selectTab;
	if(num == 1 || num == 2){
		expireScopeType[num-1] = expireScope;
		selectSales(2+num,salesURL[2+num]);
	}
	tree.setting.async.url = treeLoadUrl('getExpireTreeByCustId.jsp', '&begin=&end=&expireScope=' + expireScope + '&type=' + (--num));
	tree.refresh();
};

//动态展开树层级
function getNodeAndSelect(){
	top.GFRAME.pageMenuShow('Sales','mainTree.jsp?school_id='+login_user.id,top.bt[1]);
	if(selectTab) getselect('treeCustom',0,'treeItemOver',true);
	var args = getNodeAndSelect.arguments;
	var node = {}, app = function(){
		if(args.length == 1){
			//节点展开层数小于三
			node = tree.getNodeByParam('id',args[0],null);
		}else if(tree.getNodeByParam('id',args[args.length-1],null)){
			//选中节点存在展开层
			node = tree.getNodeByParam('id',args[args.length-1],null);
			if(!node.open)
				tree.reAsyncChildNodes(node, "refresh");
		}else{
			//选中节点未在展开树层级
			for(var i = args.length-1; i >= 0; i--){
				node = tree.getNodeByParam('id',args[i],null);
				if(node){
					if(!node.open)
						tree.reAsyncChildNodes(node, "refresh");
					setTimeout(app, 500);
					break;
				}
			}
		}
		tree.selectNode(node);
		treeOnclickCallBack(node);
	};
	app();
}

//外部删除节点回调
function delNode(id){
	var node = tree.getNodeByParam("id",id,null);
	if(node){
		var parent = node.getParentNode();
		tree.removeNode(node);
		if(parent && parent.childs){
			parent.icon = picUrl + (parent.childs.length <= 0 ? 'leaf.gif' : 'folder.gif');
			tree.updateNode(parent);
		}
	}
}

//外边调用展开节点
function expandNode(id){
	var node = tree.getNodeByParam('id',id,null);
	tree.reAsyncChildNodes(node, "refresh");
}

//外边调用添加节点
function addNodeCallback(pid,obj){
	var _node = tree.getNodeByParam('id',pid,null);
	if(_node){
		if(!_node.isParent){
			_node.icon = picUrl + 'folder.gif';
			tree.updateNode(_node);
		}
		var icon = picUrl + (obj.leaf ? 'leaf.gif' : 'folder.gif');
		var title = getNodeTitle(obj.text);
		tree.addNodes(_node,{ id: obj.id, name: obj.text, isParent: obj.isParent, icon: icon, title: title},true);
	}
}

//外边调用移动节点
function moveNodeCallback(pid,obj){
	var node = tree.getNodeByParam('id',pid,null);
	if(node && obj && node.id == obj.getParentNode().id) return;
	if(node && confirm(top.lg.moveCustom[0]+'\''+obj.text.split('(')[0]+'\''+top.lg.moveCustom[1]+'\''+node.text.split('(')[0]+'\''+top.lg.moveCustom[2]+'')){
		$.ajax({
			url : 'changeSchoolRelation.jsp',
			type : 'POST',
			data : {"custId": obj.id,"parentId":node.id,"schoolId":login_user.id},
			dataType: 'json',
			success : function(res ,options) {
				if(res.success){
					tree.moveNode(node, obj, 'inner');
					top.reloadTreeRequest("reloadTree=1&from_id="+obj.id+"&to_id="+node.id+"&need_num=1&op_type=move");
					reloadTreeFlag = {taxfee:false,revenue:false,message:false,overtree:false,homesale_q:false,homesale_b:false};
					if(workIndex == 2){selectSales(2,salesURL[2]);}
					setTimeout(function(){tree.reAsyncChildNodes(node, "refresh");},200);
				}else{
					alert(top.lg.moveCustomFail);
				}
			}
		});	
	}
}

//外边查询是否存在节点 
function existNode(id){
	var _node = tree.getNodeByParam('id',id,null);
	return _node;
}
//外边调用更新节点
function updateNodeCallback(id,txt){
	var node = tree.getNodeByParam('id',id,null);
	if(node){
		var tem = node.name.split("(")[1];
		node.name = txt+"("+tem;
		tree.updateNode(node);
	}
}

















